using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using NetWork;
using NetWork.Layer;
using ProtoBuf.Message;

namespace NetWork
{
    public class NetTickCtrl : MonoBehaviour
    {
        private List<HTTPManager> https = new List<HTTPManager>();
        private List<SocketController> sockets = new List<SocketController>();
        private static NetTickCtrl _ins = null;

        public static NetTickCtrl Instance
        {
            get
            {
                if (_ins == null)
                {
                    GameObject obj = GameObject.Find("/ManagerController/NetTick");
                    _ins = obj.GetComponent<NetTickCtrl>();
                }
                return _ins;
            }
        }
        

        public void InsertHttp(HTTPManager http)
        {
            https.Add(http);
        }

        public void InsertSocket(SocketController sock)
        {
            sockets.Add(sock);
        }

        public void RemoveHttp(string name)
        {
            for (int i = 0; i < https.Count; i++)
            {
                if (https[i].Name == name)
                {
                    https.RemoveAt(i);
                    break;
                }
            }
        }

        public void RemoveSocket(string name)
        {
            int removeId = -1;
            for (int i = 0; i < sockets.Count; i++)
            {
                if (sockets[i].Name == name)
                {
                    removeId = i;
                    break;
                }
            }
            if (removeId != -1)
            {
                sockets.RemoveAt(removeId);
            }
        }

        void Update()
        {
            for (int i = 0; i < https.Count; i++)
            {
                if (https[i] != null)
                {
                    https[i].Tick();
                }
                else
                {
                    https.RemoveAt(i--);
                }
            }
            for (int j = 0; j < sockets.Count; j++)
            {
                if (sockets[j] != null)
                {
                    sockets[j].Tick();
                }
                else
                {
                    sockets.RemoveAt(j--);
                }
            }
        }

        public void OnDestroy()
        {
            if(sockets != null)
            {
                for (int i = 0; i < sockets.Count; ++i)
                {
                    sockets[i].Disconnect();
                }
            }
        }

        public void OnApplicationPause(bool pause)
        {
            Debug.LogWarning("pause " + pause);
            for (int i = 0; i < sockets.Count; ++i)
            {
                CSEnterBackgroud cseb = new CSEnterBackgroud();
                cseb.exit = pause ? 1 : 0;
                sockets[i].Send(OpDefine.CSEnterBackgroud, cseb);
            }
        }
    }
}